<!DOCTYPE html>
<html>

  <head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>
    操作系统模拟实验(银行家算法)
    </title>
  <link type="application/atom+xml" rel="alternate" href="/feed.xml" title="虚实" />
  
  <style>
  table{
    border-left:1px solid #000000;border-top:1px solid #000000;
    width: 100%;
    word-wrap:break-word; word-break:break-all;
  }
  table th{
  text-align:center;
  }
  table th,td{
    border-right:1px solid #000000;border-bottom:1px solid #000000;
  }
  </style>

  <meta name="description" content="这几个实验都是上课时候一两小时实现的,因为老师给出的参考代码有些惨不忍睹(虽然我写的也没好到哪去).因为时间有限,就没用C++.">
  <link rel="stylesheet" href="/css/main.css">
  <link rel="stylesheet" href="/css/toc.css">
  <link rel="canonical" href="/2014/12/09/%e6%93%8d%e4%bd%9c%e7%b3%bb%e7%bb%9f%e6%a8%a1%e6%8b%9f%e5%ae%9e%e9%aa%8c%e9%93%b6%e8%a1%8c%e5%ae%b6%e7%ae%97%e6%b3%95/">
  <link rel="alternate" type="application/rss+xml" title="虚实" href="/feed.xml" />
  <link rel="stylesheet" href="/css/highlight.min.css">
  <link href="//cdn.staticfile.org/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet"media="all">
</head>


  <body>

    <header class="site-header">

  <div class="wrapper">
    <div>
      <a class="site-title" href="/">虚实</a>
      <div class="site-pages">
		<a class="site-page" href="/archive/">归档</a>
		<a class="site-page" href="/categories/">分类</a>
		<a class="site-page" href="/about/">关于</a>
		<a class="site-page" href="/friend-links/">友情链接</a>
        <a class="site-page" href="/recommends/">推荐</a>
      </div>
      <p class="site-sub-title">记录下折腾和学习的过程</p>
    </div>

  </div>

</header>


    <div class="page-content">
      <div class="wrapper">
        <div class="post">

  <header class="post-header">
    <h1 class="post-title">操作系统模拟实验(银行家算法)</h1>
    <p class="post-meta">Dec 9, 2014 • admin</p>

	<p class="post-meta"> categories :   <a href="/categories/#操作系统"> 操作系统 </a>  </p>
    <div id="show_qrcode">
        <a>扫描二维码</a>
        <div id="qrcode" style="display:none;position:absolute;z-index:1"></div>
    </div>
  </header>
  <div class="nav">
      <div id="toc" class="toc"></div>
  </div>
  <article class="post-content">
    <p>这几个实验都是上课时候一两小时实现的,因为老师给出的参考代码有些惨不忍睹(虽然我写的也没好到哪去).因为时间有限,就没用C++.</p>

<p>同样是因为时间有限,仅供参考,有bug概不负责.</p>

<p>代码如下</p>

<pre class="prettyprint lang-py"># -*- coding: utf-8 -*-
class Bank(object):
    def __init__(self):
        self.totalpro = 0
        self.process = []
        self.res_num = 4 
        self.res_type = ['A', 'B', 'C', 'D']
        self.Resources =  {'A':10, 'B':9, 'C':8, 'D':7}
        self.Available = {'A':10, 'B':9, 'C':8, 'D':7}
        self.Allocation = {}
        self.Need = {}

    def createpc(self, pno, need):
        if pno in self.process:
            print "process",pno,"exists"
            return 0
        self.process.append(pno)
        self.totalpro += 1
        need = self.list2dict(need)
        for i in need:
            if need[i] &gt; self.Available[i]:
                print "process",pno,"need : ",i,"more than available"
                return 0
        self.Need[pno] = need
        self.Allocation[pno] = dict(zip(self.res_type,
                                   [0 for i in xrange(self.res_num)]))

    def deletepc(self, pno):
        if pno not in self.process:
            print "process",pno,"not exists"
            return 0
        self.free(pno)
        self.Need.pop(pno)
        self.Allocation.pop(pno)
        self.process.remove(pno)
        self.totalpro -= 1
        print "delete process success"
        return 1
        
        
    def allocate(self, pno, request):
        request = self.list2dict(request)
        for i in request:
            if request[i] &gt; self.Need[pno][i]:
                print "process",pno,"request more than needed"
                return 0
            else:
                self.Need[pno][i] -= request[i]
            if request[i] &lt; self.Available[i]:
                self.Available[i] -= request[i]
            else:
                print  "process",pno,"request : ",i,"more than available"
                return 0
            self.Allocation[pno][i] += request[i]

        if not self.issafe(pno):
            print "not safe"
            self.free(pno)
        else:
            print "request safe!"

    def free(self,pno):
        for i in self.res_type:
            self.Available[i] += self.Allocation[pno][i]
            self.Need[pno][i] += self.Allocation[pno][i]
            self.Allocation[pno][i] = 0
            
            
    def issafe(self, pno):
        #decide is safe
        print "checking safety"
        safe = True
        Finish = {}
        Work = dict(zip(self.res_type,
                                   [0 for i in xrange(self.res_num)]))
        for i in self.Available:
            Work[i] += self.Available[i]
        for p in self.process:
            Finish[p] = False
            print p,Finish[p]

        for p in self.process:
            for i in self.Need[p]:
                if pno != p and self.Need[p][i] &lt; Work[i]:
                    Work[i] += self.Allocation[p][i]
                    Finish[p] = True

        for p in self.process:
            if pno != p and Finish[p] == False:
                safe = False
                return safe
            print p,Finish[p]
        return safe
            
        

    def list2dict(self,request):
        return dict(zip(self.res_type, request))
        
    def show(self):
        print "System Resources : "
        for i in self.res_type:
            print  i, ":", self.Resources[i], "\t"
        print "Available Resources : "
        for i in self.res_type:
            print i, ":", self.Available[i], "\t"
        print "Need Resources : "
        for pno in self.process:
            print pno, ":"
            for i in self.res_type:
                print i, ":" ,self.Need[pno][i], "\t"
        print "Allocation Resources : "
        for pno in self.process:
            print pno, ":"
            for i in self.res_type:
                print i, ":" ,self.Allocation[pno][i], "\t"

    def show_type(self):
        out = ""
        for i in self.res_type:
            out += i+' '
        print out

def main():
    bank = Bank()
    print "input 0 for create a process"
    print "input 1 for request resources"
    print "input 2 for delete a process"
    print "input 3 for show status"
    while(1):
        act = input("what to do : ")
        if act == 0:
            print "input pno"
            pno = input()
            bank.show_type()
            need = map(int, raw_input().split())
            bank.createpc(pno, need)
        elif act == 1:
            print "input pno"
            pno = input()
            bank.show_type()
            request = map(int, raw_input().split())
            bank.allocate(pno, request)
        elif act == 2:
            print "input pno"
            pno = input()
            bank.delete(pno)
        elif act == 3:
            bank.show()
        else:
            print "error input number"
            return 0

    
if __name__ == "__main__":
    main()
        </pre>
<p>先创建,再分配资源,如果不安全就把分配的资源收回….实际上应该是试分配,这里是模拟就不计较了=.=</p>

<p>测试代码如下</p>

<pre class="prettyprint lang-py"># test 1
from bank import Bank
def test1():
    bank = Bank()
    bank.createpc(1,[5,5,5,5])
    bank.createpc(2,[5,5,5,5])
    bank.show()
    bank.allocate(1,[5,5,5,5])
    bank.show()</pre>
<p>输出结果</p>

<pre class="prettyprint lang-bsh">; Test 1
System Resources : 
A : 10  
B : 9   
C : 8   
D : 7   
Available Resources : 
A : 10  
B : 9   
C : 8   
D : 7   
Need Resources : 
1 :
A : 5   
B : 5   
C : 5   
D : 5   
2 :
A : 5   
B : 5   
C : 5   
D : 5   
Allocation Resources : 
1 :
A : 0   
B : 0   
C : 0   
D : 0   
2 :
A : 0   
B : 0   
C : 0   
D : 0   
checking safety
1 False
2 False
1 False
not safe
System Resources : 
A : 10  
B : 9   
C : 8   
D : 7   
Available Resources : 
A : 10  
B : 9   
C : 8   
D : 7   
Need Resources : 
1 :
A : 5   
B : 5   
C : 5   
D : 5   
2 :
A : 5   
B : 5   
C : 5   
D : 5   
Allocation Resources : 
1 :
A : 0   
B : 0   
C : 0   
D : 0   
2 :
A : 0   
B : 0   
C : 0   
D : 0 </pre>
<p>第二个</p>

<pre class="prettyprint lang-py"># test 2
from bank import Bank
def test2():
    bank = Bank()
    bank.createpc(1,[4,3,2,1])
    bank.createpc(2,[5,5,5,5])
    bank.show()
    bank.allocate(1,[4,3,2,1])
    bank.show()</pre>
<p>输出如下</p>

<pre class="prettyprint lang-bsh">#test 2
System Resources : 
A : 10  
B : 9   
C : 8   
D : 7   
Available Resources : 
A : 10  
B : 9   
C : 8   
D : 7   
Need Resources : 
1 :
A : 4   
B : 3   
C : 2   
D : 1   
2 :
A : 5   
B : 5   
C : 5   
D : 5   
Allocation Resources : 
1 :
A : 0   
B : 0   
C : 0   
D : 0   
2 :
A : 0   
B : 0   
C : 0   
D : 0   
checking safety
1 False
2 False
1 False
2 True
request safe!
System Resources : 
A : 10  
B : 9   
C : 8   
D : 7   
Available Resources : 
A : 6   
B : 6   
C : 6   
D : 6   
Need Resources : 
1 :
A : 0   
B : 0   
C : 0   
D : 0   
2 :
A : 5   
B : 5   
C : 5   
D : 5   
Allocation Resources : 
1 :
A : 4   
B : 3   
C : 2   
D : 1   
2 :
A : 0   
B : 0   
C : 0   
D : 0 </pre>
<p>仅供参考.</p>

  </article>

</div>
<div id="disqus_thread"></div>
<script type="text/javascript">
    /* * * CONFIGURATION VARIABLES * * */
    var disqus_shortname = 'yoursoulismine';
    
    /* * * DON'T EDIT BELOW THIS LINE * * */
    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a></noscript>
<script type="text/javascript">
    /* * * CONFIGURATION VARIABLES * * */
    var disqus_shortname = 'yoursoulismine';
    
    /* * * DON'T EDIT BELOW THIS LINE * * */
    (function () {
        var s = document.createElement('script'); s.async = true;
        s.type = 'text/javascript';
        s.src = '//' + disqus_shortname + '.disqus.com/count.js';
        (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
    }());
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://flowchart.js.org/flowchart-latest.js"></script>
<script src="/js/highlight.min.js"></script>
<script src="/js/toc.js"></script>
<script src="/js/qrcode.min.js"></script>
<script>
if (!String.prototype.format) {
    String.prototype.format = function() {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function(match, number) { 
            return typeof args[number] != 'undefined'
                ? args[number]
                : match
            ;
        });
    };
}

$('pre code').each(function(i, block) {
    hljs.highlightBlock(block);
});

$('.language-flow').each(function(i, block) {
    console.log(block);
    code = $(this).text();
    diagram = flowchart.parse(code);
    canvas_id = 'flow'+ i;
    console.log(canvas_id);
    temp = "<div id='{0}'> </div>".format(canvas_id);
    console.log(temp);
    $(this).html(temp);
    diagram.drawSVG(canvas_id, {
        'x': 0,
        'y': 0,
        'line-width': 3,
        'line-length': 50,
        'text-margin': 10,
        'font-size': 14,
    });	
});

$('#toc').toc({
    noBackToTopLinks: true,
    listType: 'ul',
    title: 'TOC',
});

var url = location.href;
console.log(url);
var qrcode = new QRCode("qrcode", {
    text: url,
    width: 128,
    height: 128,
    colorDark : "#000000",
    colorLight : "#ffffff",
    correctLevel : QRCode.CorrectLevel.H
});

$(document).ready(function () {
    $('#show_qrcode').on('mouseenter', function () {
        $('#qrcode').show();
        $(this).css({
            "text-decoration": "underline"
        });
    }).on('mouseleave', function () {
        $('#qrcode').hide();
        $(this).css({
            "text-decoration": ''
        });
    });;
});
</script>

      </div>
    </div>

    <footer class="site-footer">

  <div class="wrapper">


    <div class="footer-col-wrapper">
      <div class="footer-col  footer-col-1">
        <ul class="contact-list">
	  <li>
          <li><a href="mailto:mithrilwoodrat@gmail.com">mithrilwoodrat@gmail.com</a></li>
        </ul>
      </div>

      <div class="footer-col  footer-col-2">
        <ul class="social-media-list">
          
          <li>
            <a href="https://github.com/Mithrilwoodrat">
              <span class="icon  icon--github">
                <svg viewBox="0 0 16 16">
                  <path fill="#828282" d="M7.999,0.431c-4.285,0-7.76,3.474-7.76,7.761 c0,3.428,2.223,6.337,5.307,7.363c0.388,0.071,0.53-0.168,0.53-0.374c0-0.184-0.007-0.672-0.01-1.32 c-2.159,0.469-2.614-1.04-2.614-1.04c-0.353-0.896-0.862-1.135-0.862-1.135c-0.705-0.481,0.053-0.472,0.053-0.472 c0.779,0.055,1.189,0.8,1.189,0.8c0.692,1.186,1.816,0.843,2.258,0.645c0.071-0.502,0.271-0.843,0.493-1.037 C4.86,11.425,3.049,10.76,3.049,7.786c0-0.847,0.302-1.54,0.799-2.082C3.768,5.507,3.501,4.718,3.924,3.65 c0,0,0.652-0.209,2.134,0.796C6.677,4.273,7.34,4.187,8,4.184c0.659,0.003,1.323,0.089,1.943,0.261 c1.482-1.004,2.132-0.796,2.132-0.796c0.423,1.068,0.157,1.857,0.077,2.054c0.497,0.542,0.798,1.235,0.798,2.082 c0,2.981-1.814,3.637-3.543,3.829c0.279,0.24,0.527,0.713,0.527,1.437c0,1.037-0.01,1.874-0.01,2.129 c0,0.208,0.14,0.449,0.534,0.373c3.081-1.028,5.302-3.935,5.302-7.362C15.76,3.906,12.285,0.431,7.999,0.431z"/>
                </svg>
              </span>
              <span class="username">Mithrilwoodrat</span> 
            </a>
          </li>
          
        </ul>
      </div>
  </div>
</footer>

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-66599686-1', 'auto');
  ga('send', 'pageview');

</script>
</body>
</html>
